/**
 * 音频管理相关API
 */

const BASE_URL = 'http://localhost:8000/api/audio';

// 网络请求封装
const request = (url, options = {}) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: `${BASE_URL}${url}`,
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                'Content-Type': 'application/json',
                ...options.header
            },
            success: (res) => {
                if (res.data.code === 1) {
                    resolve(res.data.data);
                } else {
                    reject(new Error(res.data.msg || '请求失败'));
                }
            },
            fail: (err) => {
                reject(new Error(err.errMsg || '网络错误'));
            }
        });
    });
};

// 文件上传请求封装
const uploadRequest = (url, files, data = {}) => {
    return new Promise((resolve, reject) => {
        if (!files || files.length === 0) {
            reject(new Error('请选择要上传的文件'));
            return;
        }

        const uploadPromises = files.map(file => {
            return new Promise((fileResolve, fileReject) => {
                uni.uploadFile({
                    url: `${BASE_URL}${url}`,
                    filePath: file.path,
                    name: 'files',
                    formData: data,
                    success: (uploadRes) => {
                        try {
                            const result = JSON.parse(uploadRes.data);
                            if (result.code === 1) {
                                fileResolve(result.data);
                            } else {
                                fileReject(new Error(result.msg || '上传失败'));
                            }
                        } catch (e) {
                            fileReject(new Error('解析响应失败'));
                        }
                    },
                    fail: (err) => {
                        fileReject(new Error(err.errMsg || '上传失败'));
                    }
                });
            });
        });

        Promise.all(uploadPromises)
            .then(results => {
                // 合并所有上传结果
                const allFiles = [];
                results.forEach(result => {
                    if (result.files && Array.isArray(result.files)) {
                        allFiles.push(...result.files);
                    }
                });
                resolve({
                    count: allFiles.length,
                    files: allFiles
                });
            })
            .catch(reject);
    });
};

export default {
    /**
     * 获取上传凭证
     */
    getUploadToken() {
        return request('/getUploadToken');
    },

    /**
     * 上传音频文件
     */
    uploadAudio(files, roomId, folderId = null) {
        return uploadRequest('/uploadAudio', files, {
            room_id: roomId,
            folder_id: folderId
        });
    },

    /**
     * 上传音频文件（包含时长信息）
     */
    uploadAudioWithInfo(audioInfoList, roomId, folderId = null) {
        return new Promise((resolve, reject) => {
            if (!audioInfoList || audioInfoList.length === 0) {
                reject(new Error('请选择要上传的音频文件'));
                return;
            }

            // 批量上传文件
            const uploadPromises = audioInfoList.map((audioInfo, index) => {
                return new Promise((fileResolve, fileReject) => {
                    uni.uploadFile({
                        url: `${BASE_URL}/uploadAudioWithInfo`,
                        filePath: audioInfo.path,
                        name: 'file',
                        formData: {
                            room_id: roomId,
                            folder_id: folderId || '',
                            file_name: audioInfo.name,
                            file_size: audioInfo.size,
                            duration: audioInfo.duration,
                            file_type: audioInfo.type,
                            index: index
                        },
                        success: (uploadRes) => {
                            try {
                                const result = JSON.parse(uploadRes.data);
                                if (result.code === 1) {
                                    fileResolve(result.data);
                                } else {
                                    fileReject(new Error(result.msg || '上传失败'));
                                }
                            } catch (e) {
                                fileReject(new Error('解析响应失败'));
                            }
                        },
                        fail: (err) => {
                            fileReject(new Error(err.errMsg || '上传失败'));
                        }
                    });
                });
            });

            Promise.all(uploadPromises)
                .then(results => {
                    // 合并所有上传结果
                    const allFiles = [];
                    results.forEach(result => {
                        if (result.audio) {
                            allFiles.push(result.audio);
                        } else if (result.id) {
                            allFiles.push(result);
                        }
                    });
                    resolve({
                        count: allFiles.length,
                        files: allFiles
                    });
                })
                .catch(reject);
        });
    },

    /**
     * 获取文件夹列表
     */
    getFolders(roomId, parentId = null) {
        return request('/getFolders', {
            data: {
                room_id: roomId,
                parent_id: parentId
            }
        });
    },

    /**
     * 获取房间内所有文件夹（用于移动文件时显示完整树形结构）
     */
    getAllFolders(roomId) {
        return request('/getAllFolders', {
            data: {
                room_id: roomId
            }
        });
    },

    /**
     * 获取音频列表
     */
    getAudios(roomId, folderId = null) {
        return request('/getAudios', {
            data: {
                room_id: roomId,
                folder_id: folderId
            }
        });
    },

    /**
     * 创建文件夹
     */
    createFolder(roomId, name, parentId = null) {
        return request('/createFolder', {
            method: 'POST',
            data: {
                room_id: roomId,
                name: name,
                parent_id: parentId
            }
        });
    },

    /**
     * 重命名文件夹
     */
    updateFolder(folderId, name) {
        return request('/updateFolder', {
            method: 'POST',
            data: {
                folder_id: folderId,
                name: name
            }
        });
    },

    /**
     * 删除文件夹
     */
    deleteFolder(folderId) {
        return request('/deleteFolder', {
            method: 'POST',
            data: {
                folder_id: folderId
            }
        });
    },

    /**
     * 移动音频文件
     */
    moveAudio(audioId, targetFolderId) {
        return request('/moveAudio', {
            method: 'POST',
            data: {
                audio_id: audioId,
                target_folder_id: targetFolderId
            }
        });
    },

    /**
     * 重命名音频文件
     */
    renameAudio(audioId, displayName) {
        return request('/renameAudio', {
            method: 'POST',
            data: {
                audio_id: audioId,
                display_name: displayName
            }
        });
    },

    /**
     * 删除音频文件
     */
    deleteAudio(audioId) {
        return request('/deleteAudio', {
            method: 'POST',
            data: {
                audio_id: audioId
            }
        });
    },

    /**
     * 批量删除音频文件（软删除）
     */
    batchDeleteAudios(audioIds) {
        if (!Array.isArray(audioIds) || audioIds.length === 0) {
            return Promise.reject(new Error('请选择要删除的音频文件'));
        }

        // 如果后端支持批量删除接口，使用此方法
        return request('/batchDeleteAudios', {
            method: 'POST',
            data: {
                audio_ids: audioIds
            }
        }).catch(() => {
            // 如果后端不支持批量删除，使用并发调用单个删除接口
            const deletePromises = audioIds.map(audioId => this.deleteAudio(audioId));
            return Promise.all(deletePromises);
        });
    },

    /**
     * 真实删除音频文件（永久删除，包括七牛云文件）
     */
    realDeleteAudios(audioIds) {
        if (!Array.isArray(audioIds) || audioIds.length === 0) {
            return Promise.reject(new Error('请选择要删除的音频文件'));
        }

        return request('/realDeleteAudios', {
            method: 'POST',
            data: {
                audio_ids: audioIds
            }
        });
    },

    /**
     * 真实删除单个音频文件（用于进度显示）
     */
    realDeleteSingleAudio(audioId) {
        return request('/realDeleteSingleAudio', {
            method: 'POST',
            data: {
                audio_id: audioId
            }
        });
    },

    /**
     * 刷新文件夹音频统计
     */
    refreshFolderStats(roomId) {
        return request('/refreshFolderStats', {
            method: 'POST',
            data: {
                room_id: roomId
            }
        });
    },

    /**
     * 测试七牛云连接配置
     */
    testQiniuConnection() {
        return request('/testQiniuConnection', {
            method: 'POST'
        });
    },

    /**
     * 获取可选音频列表（用于音频选择弹窗）
     */
    getAvailableAudios(roomId, searchText = '', category = '', excludeIds = []) {
        return request('/getAvailableAudios', {
            data: {
                room_id: roomId,
                search: searchText,
                category: category,
                exclude_ids: Array.isArray(excludeIds) ? excludeIds.join(',') : excludeIds
            }
        });
    }
};
